import 'dart:async';
import 'package:bookshelf/entity/current_task_entity.dart';
import 'package:bookshelf/event/user_id_event.dart';
import 'package:bookshelf/page/borrow_page.dart';
import 'package:bookshelf/page/mine_page.dart';
import 'package:bookshelf/page/rank_detail_page.dart';
import 'package:bookshelf/page/rank_page.dart';
import 'package:bookshelf/page/return_page.dart';
import 'package:bookshelf/page/search_page.dart';
import 'package:bookshelf/widget/app_bar.dart';
import 'package:bookshelf/util/toast_util.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:card_swiper/card_swiper.dart';

import '../entity/book_entity.dart';
import '../entity/operate_reuqest_entity.dart';
import '../entity/reader_entity.dart';
import '../entity/setting_entity.dart';
import '../event/face_event.dart';
import '../event/icr_event.dart';
import '../event/inventory_event.dart';
import '../event/qr_event.dart';
import '../http/api.dart';
import '../http/http_helper.dart';
import '../log/logger.dart';
import '../main.dart';
import '../serial/send_helper.dart';
import '../socket/send_helper.dart';
import '../widget/auth_dialog.dart';


class Index extends StatefulWidget {
  const Index({Key? key}) : super(key: key);

  @override
  State<Index> createState() => _IndexState();
}

class _IndexState extends State<Index> {

  final RxList<BookEntity> recommendList = RxList();
  final RxList<BookEntity> readList = RxList();

  final RxList<String> bannerList = RxList();
  final RxList<String> adList = RxList();

  List<SettingEntityReader> readers = [];
  var inventoryIndex = 0;
  final List<BookEntity> _currentList = [];
  StreamSubscription? inventorySubscription;
  StreamSubscription? userSubscription;
  StreamSubscription? icrSubscription;
  StreamSubscription? qrSubscription;
  StreamSubscription? faceSubscription;
  Timer? _inventoryTimer;
  Timer? _timer;

  @override
  initState() {
    super.initState();

    _lockScreen();

    inventorySubscription = eventFactory.on<InventoryEvent>().listen((event) {
      if(canInventory){
        for (var element in event.data) {
          try{
            var currentPlace = settingEntity.place!.firstWhere((e) => (e.station.toString().padLeft(2,'0') == element.$3)
                && (e.ant!.padLeft(2,'0') == int.parse(element.$2,radix: 16).toString().padLeft(2,'0'))).place;
            BookEntity? entity = _currentList.firstWhereOrNull((e) => e.uid == element.$1);
            if(entity != null){
              if(currentPlace  == entity.place){
                entity.status = 0;
              }else{
                entity.status = 2;
              }
              entity.place = currentPlace;
              entity.placeName = _analyzePlace(currentPlace);
            }else{
              _currentList.add(BookEntity()
                ..uid = element.$1
                ..place = currentPlace
                ..placeName = _analyzePlace(currentPlace)
                ..status = 1
              );
            }
          }catch(e){
            Logger().write('uid = ${element.$1},ant = ${element.$2}, error =  $e \r\n');
          }

        }
        inventoryIndex++;
        _inventory();
      }
    });

    userSubscription = eventFactory.on<UserIdEvent>().listen((event) {
      currentTask.uid = event.uid;
      _getUser(currentTask.uid);
    });
    faceSubscription = eventFactory.on<FaceEvent>().listen((event) {
      currentTask.uid = event.uid;
      _getUser(currentTask.uid,category: 'face');
    });

    icrSubscription = eventFactory.on<IcrEvent>().listen((event) {
      _getReaderNo(event.icr);
    });

    qrSubscription = eventFactory.on<QrEvent>().listen((event) async {
      currentTask.uid = event.qr;
      _getUser(event.qr,category: 'qrcode');
    });

    _startHotTimer();
    _queryBook();
    _initData();
    _initPic();
    _getVersion();
    _days();
  }

  _days() async {
    var day = await days();
    if(day != null){
      if(day <=5 && day>0){
        Get.defaultDialog(
          title: '提示',
          titleStyle: TextStyle(
            color: const Color(0xFF000000),
            fontSize: 10.sp,
          ),
          middleText: '软件还有$day天过期',
          middleTextStyle: TextStyle(
            color: const Color(0xFF000000),
            fontSize: 8.sp,
          ),
          radius: 4.sp,
          textConfirm: '',
          // textCancel: '取消',
          barrierDismissible: true,
          confirmTextColor: const Color(0xFF007AFF),
          backgroundColor: const Color(0xD1F8F8F8),
          buttonColor: Colors.transparent,
          onConfirm: () {

          },
        );
      }
      if(day <=0){
        Get.defaultDialog(
          title: '提示',
          titleStyle: TextStyle(
            color: const Color(0xFF000000),
            fontSize: 10.sp,
          ),
          middleText: '软件已过期',
          middleTextStyle: TextStyle(
            color: const Color(0xFF000000),
            fontSize: 8.sp,
          ),
          radius: 4.sp,
          barrierDismissible: false,
          textConfirm: '',
          // textCancel: '取消',
          confirmTextColor: const Color(0xFF007AFF),
          backgroundColor: const Color(0xD1F8F8F8),
          buttonColor: Colors.transparent,
          onConfirm: () {

          },
        );
      }

    }
  }


  _getVersion(){
    version().then((value) async {
      if(value != null){
        var versionCode = await const MethodChannel('toAndroid').invokeMethod('getAppVersionCode');
        int code = int.tryParse(value.ver_code??'0')??0;
        if(code > versionCode){
          HttpHelper.instance.downLoad('${value.url??''}');
        }
      }
    });
  }

  _analyzePlace(String? place){
    if(place == null){
      return '';
    }
    // String room = place.substring(0,2);
    String column = place.substring(2,6);
    String side = place.substring(6,8);
    String knot = place.substring(8,10);
    String floor = place.substring(10,12);
    return '${settingEntity.roomName}$column排${side=='01'?'A面':'B面'}$knot列$floor层';
  }


  _startHotTimer(){
    _timer = Timer.periodic(const Duration(seconds:600), (timer) async {
      _initData();
      _initPic();
      if(_inventoryTimer == null){
        _queryBook();
      }
    });
  }

  _lockScreen() {
    const MethodChannel('toAndroid').invokeMethod('hideBar');
  }

  _inventory(){
    if(canInventory) {
      if(inventoryIndex<readers.length){
        hfSerialPortHelper.sendData(inventoryAll(readers[inventoryIndex].station!));
      }else{
        _renew();
      }
    }
  }

  _renew() {
    var list  = [];
    for (var element in _currentList.where((element) => element.status != 0)) {
      if(element.status==-1 || element.status==2){
        list.add(OperateReuqestEntity()
          ..rfid = element.uid
          ..place = element.place
          ..category = 'on'
          ..toJson()
        );
      }
      if(element.status==1){
        list.add(OperateReuqestEntity()
          ..rfid = element.uid
          ..place = element.place
          ..category = 'off'
          ..toJson()
        );
      }
    }
    _currentList.removeWhere((element) => element.status == -1);
    if(list.isEmpty){
      print('list empty');
      return;
    }

    operate(list);
  }


  _queryBook() {
    findRfidList().then((value){
      if(value != null){
        for (var element in value) {
          _currentList.add(BookEntity()
            ..status = -1
            ..place = element.currPlace
            ..uid = element.rfid
          );
        }
        if(settingEntity.main??false){
          _startInventory();
        }
      }
    });
  }

  _startInventory(){
    if(settingEntity.reader != null){
      for (var element in settingEntity.reader!) {
        if(element.state == 0){
          readers.add(element);
        }
      }
      if(readers.isEmpty){
        return;
      }
      _inventoryTimer = Timer.periodic(Duration(seconds:settingEntity.inventoryTime??30), (timer) async {
        inventoryIndex = 0;
        for (var element in _currentList) {
          element.status = -1;
        }
        _inventory();
      });
    }
  }

  _initPic(){
    asset('default').then((value){
      if(value != null && value.isNotEmpty){
        bannerList.clear();
        for (var element in value) {
          bannerList.add(element.url!);
        }
      }
    });
    asset('screen').then((value){
      if(value != null && value.isNotEmpty){
        adList.clear();
        for (var element in value) {
          adList.add(element.url!);
        }
      }
    });
  }

  _initData() {
    hot().then((value){
      if(value != null){
        readList.clear();
        readList.addAll(value);
      }
    });

    recommend().then((value){
      if(value != null){
        recommendList.clear();
        recommendList.addAll(value);

      }
    });
  }

  _getReaderNo(no) async {
    if(Get.isDialogOpen != null && Get.isDialogOpen!){
      Get.back();
    }
    var data = await findBind(no);
    if(data != null){
      currentTask.uid = data;
      _getUser(currentTask.uid);
    }
  }

  _getUser(uid,{String category = 'uid'}) async {
    if(Get.isDialogOpen != null && Get.isDialogOpen!){
      Get.back();
    }
    timer.cancel();
    ReaderEntity? reader = await findReader(uid,category: category);
    if(reader != null && reader.no != null && reader.no!.isNotEmpty){
      // if(!reader.validReader! && currentTask.authType == 2){
      //   currentTask.clear();
      //   toastWarn('身份证未认证');
      //   return;
      // }
      currentTask.uid = reader.no;
      currentTask.uName = reader.name;
      currentTask.readerEntity = reader;
      if(currentTask.task == Task.borrow){
        Get.to(()=> const Borrow());
      }
      if(currentTask.task == Task.toMine){
        Get.to(()=> const Mine(),arguments: reader);
      }
    }else{
      toastWarn('身份未认证');
      currentTask.clear();
    }
  }


  @override
  void dispose() {
    inventorySubscription?.cancel();
    inventorySubscription = null;
    userSubscription?.cancel();
    userSubscription = null;
    faceSubscription?.cancel();
    faceSubscription = null;
    icrSubscription?.cancel();
    icrSubscription = null;
    // socketHelper.close();
    _inventoryTimer?.cancel();
    _inventoryTimer = null;
    qrSubscription?.cancel();
    qrSubscription = null;
    _timer?.cancel();
    _timer = null;
    clock.cancel();
    saver.cancel();
    try{
      ledSerialPortHelper.close();
      idSerialPortHelper.close();
    }catch(e){
      print(e);
    }

    super.dispose();
  }

  _searchBarWidget(){
    return Container(
        width: double.infinity,
        height: 35.h,
        decoration:const BoxDecoration(
          image: DecorationImage(
            fit: BoxFit.fill,
            image: AssetImage(
              "assets/images/search_bg.png",
            ),
          ),
        ),
        padding: EdgeInsets.only(left:8.r,right: 2.r),
        margin:  EdgeInsets.only(bottom: 8.r,top: 8.r,left: 8.r,right: 8.r),
        child: InkWell(
          onTap: (){
             Get.to(()=> const Search());
            //Get.to(()=> const Book());
          },
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Image.asset("assets/images/search_icon.png",width: 22.w,fit: BoxFit.fitWidth,),
              SizedBox(
                width: 260.w,
                child: Text("搜索书名 作者", style: TextStyle(color: Colors.black54,fontSize: 14.sp),),
              ),
              Image.asset("assets/images/search.png",width: 66.w,fit: BoxFit.fitWidth,)
            ],
          ),
        )
    );
  }

  _swiper(){
    return Container(
      height: 160.h,
      margin: EdgeInsets.only(top: 8.r,left: 8.r,right: 8.r),
      child: Obx(() => Swiper(
        itemBuilder: (BuildContext context,int index){
          return Container(
            clipBehavior: Clip.hardEdge,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(8),
            ),
            child: Image.network(bannerList[index], fit: BoxFit.cover,),
          );
        },
        itemCount: bannerList.length,
        itemWidth: 360.w,
        itemHeight: 160.h,
        autoplay: true,
        autoplayDelay: 5000,
        // layout: SwiperLayout.STACK,
        pagination: const SwiperPagination(),
        // control: SwiperControl(),
      )),
    );
  }



  // _adSwiper(){
  //   return Swiper(
  //     itemBuilder: (BuildContext context,int index){
  //       return Container(
  //         clipBehavior: Clip.hardEdge,
  //         decoration: const BoxDecoration(
  //           color: Colors.white
  //         ),
  //         child: Image.network(adList[index],fit: BoxFit.cover),
  //       );
  //     },
  //     itemCount: adList.length,
  //     itemHeight: double.infinity,
  //     autoplay: true,
  //     autoplayDelay: 5000,
  //     // layout: SwiperLayout.STACK,
  //     // control: SwiperControl(),
  //   );
  // }

  _ad(){
    return Stack(
      children: [
        for (int i = 0; i < adList.length; i++)
          if(i<=saver.index.value%adList.length)...[
            Image.network(adList[i],width: double.infinity,height:double.infinity,fit: BoxFit.fill)
          ]
      ],
    );
  }

  _action(){
    return Padding(padding: EdgeInsets.only(left: 8.r,right: 8.r),child: Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        InkWell(
          onTap: () async {
            if(settingEntity.action??true){
              currentTask.task = Task.borrow;
              AuthDialog().authTypeDialog();
            }else{
              toastWarn('功能暂不开放');
            }

          },
          child: Image.asset("assets/images/borrow_bg.png",width: 122.w,fit: BoxFit.fitWidth,),
        ),
        InkWell(
          onTap: (){
            if(settingEntity.action??true){
              Get.to(()=>const Return());
            }else{
              toastWarn('功能暂不开放');
            }
          },
          child: Image.asset("assets/images/return_bg.png",width: 122.w,fit: BoxFit.fitWidth,),
        ),
        InkWell(
          onTap: () async {
            if(settingEntity.action??true){
              currentTask.task = Task.toMine;
              AuthDialog().authTypeDialog();
            }else{
              toastWarn('功能暂不开放');
            }
          },
          child: Image.asset("assets/images/mine_bg.png",width: 122.w,fit: BoxFit.fitWidth,),
        ),
      ],
    ),);
  }


  _rank(type){
    return Container(
      width: double.infinity,
      height: 152.h,
      margin: EdgeInsets.only(left:8.r,right: 8.r,top: 8.r),
      decoration:  BoxDecoration(
        color: const Color.fromRGBO(255, 255, 255, 0.4),
        borderRadius: BorderRadius.all(Radius.circular(4.r)),
      ),
      padding: EdgeInsets.only(left:8.r,right: 8.r,top: 8.r),
      child: Column(
        // crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            width: 386.w,
            height: 20.h,
            child: Stack(
              alignment: AlignmentDirectional.center,
              children: [
                Positioned(left:0,child: Text(type=='read'?'借阅排行':'推荐排行',style: TextStyle(fontSize: 13.sp,color: Colors.white),)),
                Positioned(left:0,top:19.h,child: Image.asset("assets/images/line.png",width: 54.w,fit: BoxFit.fitWidth,),),
                Positioned(right:0,child: InkWell(
                    onTap: (){
                      Get.to(()=>const Rank(),arguments: type);
                    },
                    child:Row(
                      children: [
                        Text('查看更多',style: TextStyle(fontSize: 8.sp,color: Colors.white),),
                        Icon(Icons.chevron_right,color: Colors.white,size: 8.sp,),
                      ],
                    )
                ),),
              ],
            ),
          ),
          SizedBox(
              height: 116.h,
              child: Obx(() => ListView.separated(
                itemBuilder: (context, index) {
                  return _listItem(index,type);
                },
                scrollDirection: Axis.horizontal,
                itemCount: type=='read'?(readList.length>5?5:readList.length):(recommendList.length>5?5:recommendList.length),
                separatorBuilder: (BuildContext context, int index) {
                  return VerticalDivider(
                      width: 8.w,
                      color: Colors.transparent);
                },
              ))
          )
        ],
      ),
    );
  }

  _listItem(index,type){
    BookEntity item = type == 'read'?readList[index]:recommendList[index];
    return InkWell(
      onTap: (){
        Get.to(()=>const RankDetail(),arguments: (item.book_id,item.title,'index'));
      },
      child: Container(
          margin: EdgeInsets.only(top: 8.r),
          child: Stack(
            alignment: AlignmentDirectional.topCenter,
            children: [
              // ColorFiltered(
              //   colorFilter: ColorFilter.mode(
              //     Colors.white.withOpacity(0.0),
              //     BlendMode.clear,
              //   ),
              //   child:  Image.network('${item.cover}',width: 67.w,height:90.h,fit: BoxFit.fill,
              //     errorBuilder: ( BuildContext context, Object error, StackTrace? stackTrace,){
              //       return  Image.asset('assets/images/default.png',width: 67.w,height:90.h,fit: BoxFit.fill);
              //     },),
              // ),
              Image.network('${item.cover}',width: 67.w,height:90.h,fit: BoxFit.fill,
                errorBuilder: ( BuildContext context, Object error, StackTrace? stackTrace,){
                  return  Image.asset('assets/images/default.png',width: 67.w,height:90.h,fit: BoxFit.fill);
                },),
              Positioned(top:0,right:0,child:Image.asset("assets/images/${ type == 'read'?'rank_${index+1}':'recommend_icon'}.png",width: 17.w,fit: BoxFit.fitWidth,),),
              SizedBox(height: 5.h,),
              Positioned(top:95.h,child: SizedBox(width:60.w,child: Text('${item.title}',style: TextStyle(color: Colors.white,fontSize: 8.sp),textAlign: TextAlign.center,),),)
            ],
          )
      ),
    );
  }

  _version(){
    return Container(
      margin: EdgeInsets.only(top: 6.r,left: 8.r,right: 8.r),
      child: Stack(
        children: [
          Text('${settingEntity.columnNo}排',style: TextStyle(color: Colors.white,fontSize: 8.sp)),
          Align(child: Text('版本4.5.2',style: TextStyle(color: Colors.white,fontSize: 8.sp)),)
        ],
      )
    );
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () => FocusScope.of(context).requestFocus(FocusNode()),
        child: Scaffold(
          body: Stack(
            children: [
              Container(
                  width: double.infinity,
                  height: double.infinity,
                  decoration: const BoxDecoration(
                    image: DecorationImage(
                      fit: BoxFit.fill,
                      image: AssetImage(
                        "assets/images/bg.png",
                      ),
                    ),
                  ),
                  child: Column(
                    children: [
                      appBar(isIndex: true),
                      _swiper(),
                      _searchBarWidget(),
                      _action(),
                      _rank('read'),
                      _rank('recommend'),
                      _version(),
                    ],
                  )
              ),
              Obx(() => Visibility(
                  visible:saver.isSleep.value,
                  child: InkWell(
                    onTap: (){
                      saver.isSleep.value = false;
                      saver.start();
                    },
                    child: adList.isEmpty?Container(
                      width: double.infinity,
                      height: double.infinity,
                      padding: EdgeInsets.only(top: 200.h),
                      decoration: const BoxDecoration(
                          color: Colors.black
                      ),
                      child: Column(
                        children: [
                          Text('${clock.day.value} ${clock.weekDay.value}',style: TextStyle(fontSize: 30.sp,color: Colors.white),),
                          Text(clock.time.value,style: TextStyle(fontSize: 50.sp,color: Colors.white),),
                        ],
                      ),
                    ): _ad()
                  )
              ))
            ],
          )
        ));
  }
}